﻿// Copyright (c) Vitaly Kamiansky. All rights reserved. 
// See License.txt in the project root.

using System;
using System.Threading.Tasks;

namespace Property.Workers
{
    public class BackgroundWorker<T> : Worker<T>
    {
        public BackgroundWorker(Func<T> work)
        {
            _Work = work;
        }

        private readonly Func<T> _Work;

        //=//

        private Task<T> WorkerTaskState;
        public override bool IsRunning { get { return WorkerTaskState == null ? false : WorkerTaskState.Status == TaskStatus.Running; } }

        private T ResultState;
        public override T Result { get { return ResultState; } }

        private Exception ExceptionState;
        public override Exception Exception { get { return ExceptionState; } }

        public override async void Go()
        {
            if (IsRunning) return;
            try
            {
                ResultState = default(T);
                ExceptionState = null;
                ResultState = await(WorkerTaskState = Task.Factory.StartNew(_Work, TaskCreationOptions.LongRunning));
            }
            catch (Exception e)
            {
                ExceptionState = e;
            }
            finally
            {
                OnFinished();
            }
        }
    }
}
